<?php
namespace app\wechat\controller;

use tp5_lib\wechat\utility\WechatOAuth;
use tp5_lib\wechat\model\WechatUserModel;
use tp5_lib\wechat\model\WechatUserTokenModel;

/**
 * 网页授权
 */
class ClientController extends IndexController
{
    private $appid="wx421336a6c9b67c0a";
    private $appSecret="1dabf80e33b36d726fb2340e30a54af5";
    /**
     * 网页授权页面
     */
    public function index()
    {
        session("wechat_login_redirect_url",input("redirect_url",""));
        $redirect_uri= "http://tp5.1620428040.xyz/wechat/client/receivecode";
        $url=WechatOAuth::alloc($this->appid,$this->appSecret)
            ->getWebpageAuthUrl($redirect_uri);
        $this->redirect($url);
    }
    public function rejectForwarded()
    {
        if(
            isset($_SERVER["HTTP_X_FORWARDED_FOR"])
            && strpos($_SERVER["HTTP_USER_AGENT"],"MicroMessenger")
            && (!isset($_SERVER["HTTP_CONNECTION"]) || $_SERVER["HTTP_CONNECTION"]!=="keep-alive")
        ){
            header("HTTP/1.1 403 Forbidden");
            exit;
        }
    }
    public function receiveCode()
    {
        $this->redirect("updateInfo",input());
    }
    public function updateInfo(){
        $this->rejectForwarded();
        $code=input("code");
        $wechat=WechatOAuth::alloc($this->appid,$this->appSecret);

        $token_info=$wechat->getAccessToken($code);
        if(isset($token_info["errcode"])){
            $this->error("微信第三方登录失败");
        }
        $token=new WechatUserTokenModel();
        $token_info["time"]=time();
        $token_info["source"]="client";
        $token->db()->insert($token_info);

        $user_info=$wechat->getUserInfo($token_info["openid"],$token_info["access_token"]);
        if(isset($user_info["errcode"])){
            $this->error("获取用户信息失败");
        }
        $user=new WechatUserModel();
        if(isset($user_info["unionid"])){
            $record=$user->db()->where(["unionid"=>$user_info["unionid"]])->order("id","desc")->find();
        }
        else{
            $record=$user->db()->where(["openid"=>$user_info["openid"]])->order("id","desc")->find();
        }
        $user_info["update_time"]=time();
        $user_info["privilege"]=json_encode($user_info["privilege"]);
        if($record){
            $user->db()->where(["id"=>$record["id"]])->update($user_info);
            if($record["user_id"]){
                $user=$this->logic->doLogin($record["user_id"]);
                $this->loginRedirect($user);
            }
            else{
                $this->redirect("bindAccount",["id"=>$record["id"]]);
            }   
        }
        else{
            $user_info["create_time"]=time();
            $id=$user->db()->insertGetId($user_info);
            $this->redirect("bindAccount",["id"=>$id]);
        }
    }
}
